package com.coocaa.app.lib.cleaner.scanner.scannerapk;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.coocaa.app.lib.cleaner.scanner.config.ConfigManagerFactory;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Eric on 2017/4/11.
 */

public class ScanApkUtils {
    private static final String tag = "demo";
    private static final String DATA_PATH = "/data/data/";
    private Context mContext = null;
    private List<ScanData> scanList = new ArrayList<ScanData>();
    private boolean forceStop = false;

    private static final String[] keepArray = {
            "/data/data/com.tianci.movieplatform/app_download/theme",
            "/data/data/com.tianci.movieplatform/files/plugin",
            "com.tianci.appstore/files/coocaa_app/download",
            "com.tianci.appstore/files/13_upgrade.apk",
            "com.tianci.appstore/files/7_upgrade.apk",
            "com.tianci.appstore/cache/silent_downloader",
            "com.tianci.appstore/files/silent_downloader",
            "com.tianci.appstore/coocaa_app/download"
    };

    public ScanApkUtils(Context mContext) {
        this.mContext = mContext;
    }

    public synchronized List<ScanData> scanApkList() {
        setForceStop(false);
        scanList.clear();
        List<String> list = getScanPath();
        if (list != null && list.size() > 0) {
            for (String path : list) {
                Log.d("demo", "ScanApkUtils  scanApkList path: " + path);
                scanAPK(path);
            }
        }
        Log.d("demo", " scanApkList scanList.size(): " + scanList.size());
        return scanList;
    }

    /**
     * 扫描两个目录：
     * 1，/data/data
     * 2,如果有sdcard，且是虚拟sdcard的所有目录
     */
    private List<String> getScanPath() {
        List<String> pathList = new ArrayList<String>();
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
//                && Environment.isExternalStorageEmulated()
                ) {
            try {
                String extralDataPath = Environment.getExternalStorageDirectory().getPath();
                Log.d("demo", "ScanApkUtils getScanPath extralDataPath: " + extralDataPath);
                if (!TextUtils.isEmpty(extralDataPath))
                    pathList.add(extralDataPath);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        pathList.add(DATA_PATH);
        return pathList;
    }

    public void setForceStop(boolean f) {
        forceStop = f;
    }

    private void scanAPK(String path) {
        if (forceStop) {
            Log.d(tag, "scanAPK---forceStop!!");
            return;
        }
        File rootDir = new File(path);
        if (!rootDir.exists()) {
//            Log.d(tag, "scanAPK---error path!!");
            return;
        }
        if (!rootDir.isDirectory()) {
            if (path.toLowerCase().endsWith(".apk")) {
                String filepath = rootDir.getAbsolutePath();
                Log.d(tag, "-------------ScanApkUtils---scanAPK---" + filepath);
                ScanData data = getApkInfo(filepath);
                if (data != null)
                    scanList.add(data);
            }
        } else {
            String[] fileList = rootDir.list();
            if (fileList != null && fileList.length > 0) {
                for (int i = 0; i < fileList.length; i++) {
//                    if (!fileList[i].startsWith(".")) {
                        path = rootDir.getAbsolutePath() + "/" + fileList[i];
//                        Log.d(tag, "-----------ScanApkUtils----scanpath---" + path);
                        scanAPK(path);
//                    }
                }
            }
        }
        return;
    }

    private ScanData getApkInfo(String apkPath) {
        Log.d("demo", "ScanApkUtils  getApkInfo apkPath:" + apkPath);
        for(String keep:keepArray){
            if(apkPath.toLowerCase().contains(keep))
                return null;
        }
        List<String> keepList = ConfigManagerFactory.factory.instance().load().getFileKeepFiles();
        if(keepList != null && keepList.size() > 0){
            for(String path:keepList){
                if(path.endsWith(".apk") && apkPath.toLowerCase().contains(path)){
                    return null;
                }
            }
        }
        PackageManager pm = mContext.getPackageManager();
        ScanData data = new ScanData();
        PackageInfo pkgInfo = pm.getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES);
        if (pkgInfo != null) {
            ApplicationInfo appInfo = pkgInfo.applicationInfo;
//            appInfo.sourceDir = apkPath;
//            appInfo.publicSourceDir = apkPath;
//            String appName = pm.getApplicationLabel(appInfo).toString();// 得到应用名
            long size = new File(apkPath).length();
            int version = pkgInfo.versionCode;
            String packageName = appInfo.packageName; // 得到包名
            int installedVersion = getVersionCode(mContext, packageName);
            data.path = apkPath;
            data.pkg = packageName;
            data.length = size;
            data.versionCode = version;
            if (version > installedVersion) {
                //需求上没有要求这么详细
//                data.apkType = 3;
//                if(installedVersion == -1)
//                    data.apkType = 1;
                data.apkType = 1;
                if(data.pkg.equals("com.tianci.appstore"))
                    return null;
            }else {
                data.apkType = 2;
            }
            return data;
        } else {
            Log.d("scan", "fake apk!!!!!!!!!");
            data.pkg = "";
            data.path = apkPath;
            data.versionCode = 0;
            data.length = new File(apkPath).length();
            data.apkType = 0;
        }
        return data;
    }

    private static int getVersionCode(Context context, String pkg) {
        PackageManager mPackageManager = context.getApplicationContext().getPackageManager();
        try {
            return mPackageManager.getPackageInfo(pkg, 0).versionCode;
        } catch (Exception e) {
            return -1;
        }
    }

    public class ScanData {
        public String pkg;
        public int versionCode;
        public String path;
        public long length;
        public int apkType;  //  0:无效apk  1:未安装  2：已安装  3：可更新
    }

}
